/**
 * 
 */
package com.gragra.util;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * implementation for mapping strings to int values, that should be at its most efficient when it is used
 * for large amounts of strings.
 * @author Christoph Teichmann
 * created Nov 3, 2012 12:42:27 PM
 * @version 0.1
 */
public class StringToInt
{
	/**
	 * the reverse of the codes used for the different strings
	 */
	private static final Int2ObjectMap<String> codeReverse = new Int2ObjectOpenHashMap<String>();
	/**
	 * the codes used
	 */
	private static final Object2IntOpenHashMap<String> code;
	/**
	 * 
	 */
	static
	{
		code = new Object2IntOpenHashMap<String>();
		code.defaultReturnValue(-1);
	}
	/**
	 * counts the used codes
	 */
	private static final AtomicInteger i = new AtomicInteger(0);
	/**
	 * makes sure that there is a code for the given string and returns it
	 *
	 * @param toCode
	 * @return
	 */
	public static int ensure(String toCode)
	{
		int k = code.getInt(toCode);
		if(k<0)
		{
			k = i.getAndIncrement();
			String s = new String(toCode);
			synchronized(code)
			{
				codeReverse.put(k, s);
				code.put(s, k);
			}
		}
		return k;
	}
	/**
	 * gives the string for the given code or null if there is no such string
	 *
	 * @param k
	 * @return
	 */
	public static String reverse(int k)
	{return codeReverse.get(k);}
}